<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"/>
    <title>Jpcap Tutorial</title>
    <link rel="stylesheet" href="../style.css" type="text/css"/>
    <style type="text/css">
        pre {
            font-family: monospace, fixed;
        }

        pre.code {
            border: 1px solid #cccccc;
            margin: 4px 8px 4px 2px;
            padding: 4px 6px;
            background-color: #f5f5f5;
            overflow: auto;
            white-space: pre;
            font-family: monospace, fixed;
        }

        .comment {
            color: #800000;
        }
    </style>
</head>
<body>
<div style="text-align: center;"><h1>Jpcap
    Tutorial</h1>
    1.0 (for Jpcap 0.7)<br/>
    <br/>
    <div style="text-align: left;">Author:<br/>
        &nbsp;&nbsp;&nbsp; Keita Fujii (kfujii@uci.edu)<br/>
        Home page:<br/>
        &nbsp;&nbsp;&nbsp; <a href="http://netresearch.ics.uci.edu/kfujii/jpcap/doc/index.html">http://netresearch.ics.uci.edu/kfujii/jpcap/doc/index.html</a><br/>
        <hr style="width: 100%; height: 2px;"/>
        <span style="font-weight: bold;"><a name="toc"></a><big>Table
of Contents</big></span><br/>
        <ul>
            <li><a href="#intro">Introduction</a></li>
            <li><a href="#tutorial">Jpcap tutorial: a step by
                step guide for using Jpcap</a></li>
            <ul>
                <li><a href="#obtain">Obtain
                    the&nbsp;list
                    of network interfaces</a></li>
                <li><a href="#open">Open a network interface</a></li>
                <li><a href="#capture">Capture packets from the
                    network interface</a></li>
                <li><a href="#set">Set capturing filter</a></li>
                <li><a href="#save">Save captured packets into a
                    file</a></li>
                <li><a href="#read">Read saved packets from a file</a></li>
                <li><a href="#send">Send packets through a
                    network interface</a></li>
            </ul>
        </ul>
        <hr style="width: 100%; height: 2px;"/>
        <h2><a name="intro"></a>Introduction</h2>
        This document describes how to develop applications using Jpcap. It
        explains the functions and classes defined in Jpcap, and also
        provides&nbsp;comprehensive descriptions on how to program using
        Jpcap by showing some example codes.<br/>
        <br/>The latest version of this document can be found at: <a
                href="http://netresearch.ics.uci.edu/kfujii/jpcap/doc/tutorial/index.html">http://netresearch.ics.uci.edu/kfujii/jpcap/doc/tutorial/index.html</a><br/>
        <br/>
        <h3>What is Jpcap</h3>
        Jpcap is an open source library for capturing and sending network
        packets from Java applications. It provides facilities to:<br/>
        <ul>
            <li>capture raw packets live from the wire.&nbsp;</li>
            <li>save captured packets to an offline file, and
                read&nbsp;captured packets from an offline file.
            </li>
            <li>automatically identify packet types and generate
                corresponding Java objects (for Ethernet, IPv4, IPv6, ARP/RARP, TCP,
                UDP, and ICMPv4 packets).
            </li>
            <li>filter the packets according to user-specified rules before
                dispatching them to the application.
            </li>
            <li>send raw packets to the network</li>
        </ul>
        Jpcap is based on&nbsp;<a target="_blank" href="http://www.tcpdump.org/">libpcap</a><span
                style="font-weight: normal;">/</span><a target="_blank" href="http://www.winpcap.org/">winpcap</a><span
                style="font-weight: normal;"></span>, and is
        implemented in C and Java.<br/>
        <script type="text/javascript"><!--
        google_ad_client = "pub-0175657744917151";
        google_ad_width = 250;
        google_ad_height = 250;
        google_ad_format = "250x250_as";
        google_ad_type = "text_image";
        //2007-05-16: Jpcap
        google_ad_channel = "6260474890";
        //-->
        </script>
        <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
        </script>
        <br/>Jpcap
        has been tested on
        Microsoft Windows (98/2000/XP/Vista), Linux (Fedora, Ubuntu), Mac OS
        X (Darwin), FreeBSD, and Solaris.<br/>
        <h3>What kind of applications can be developed using Jpcap</h3>
        Jpcap can be used to develop&nbsp;many kinds of network
        applications, including (but not limited to):
        <ul>
            <li>network and protocol analyzers</li>
            <li>network monitors</li>
            <li>traffic loggers</li>
            <li>traffic generators</li>
            <li>user-level bridges and routers</li>
            <li>network intrusion detection systems (NIDS)</li>
            <li>network scanners</li>
            <li>security tools</li>
        </ul>
        <h3>What Jpcap cannot do</h3>
        Jpcap captures and sends&nbsp;packets <i>independently</i>
        from the host protocols (e.g.,&nbsp;TCP/IP). This means that Jpcap
        does not (cannot) block, filter or manipulate the traffic generated by
        other programs on the same machine: it simply "sniffs" the packets that
        transit on the wire. Therefore, it does not provide the appropriate
        support for applications like traffic shapers, QoS schedulers and
        personal firewalls.<br/>
        <br/>
        <div style="text-align: right;"><a href="#toc">Back
            to Table of Contents</a><br/>
        </div>
        <hr style="width: 100%; height: 2px;"/>
        <h2><a name="tutorial"></a>Jpcap tutorial: a
            step by step guide for using Jpcap</h2>
        <h3><a name="obtain"></a>Obtain
            the&nbsp;list of network interfaces</h3>
        When you want to capture packets from a network, the first thing you
        have to do is to obtain the list of network interfases on your machine.
        To do so, Jpcap provides <a
                href="../javadoc/jpcap/JpcapCaptor.html#getDeviceList()">JpcapCaptor.getDeviceList()</a>
        method. It returns an array of <a href="../javadoc/jpcap/NetworkInterface.html">NetworkInterface</a>
        objects.<br/>
        <br/>A <a href="../javadoc/jpcap/NetworkInterface.html">NetworkInterface</a>
        object contains some information about the corresponding network
        interface, such as its name, description, IP and MAC addresses, and
        datatlink name and description.<br/>
        <br/>The following sample code obtains the list of network
        interfaces and
        prints out their information.<br/>
        <br/>
        <div>
            <pre class="code">//Obtain the list of network interfaces<br/>NetworkInterface[] devices = JpcapCaptor.getDeviceList();<br/><br/>//for each network interface<br/>for (int i = 0; i &lt; devices.length; i++) {<br/>  //print out its name and description<br/>  System.out.println(i+": "+devices[i].name + "(" + devices[i].description+")");<br/><br/>  //print out its datalink name and description<br/>  System.out.println(" datalink: "+devices[i].datalink_name + "(" + devices[i].datalink_description+")");<br/><br/>  //print out its MAC address<br/>  System.out.print(" MAC address:");<br/>  for (byte b : devices[i].mac_address)<br/>    System.out.print(Integer.toHexString(b&amp;0xff) + ":");<br/>  System.out.println();<br/><br/>  //print out its IP address, subnet mask and broadcast address<br/>  for (NetworkInterfaceAddress a : devices[i].addresses)<br/>    System.out.println(" address:"+a.address + " " + a.subnet + " "+ a.broadcast);<br/>}</pre>
            <br/>This
            sample code may show a result like the following (on
            windows): <br/>
            <pre>0: \Device\NPF_{C3F5996D-FB82-4311-A205-25B7761897B9}(VMware Virtual Ethernet Adapter)<br/>&nbsp;&nbsp;&nbsp; data link:EN10MB(Ethernet)<br/>&nbsp;&nbsp;&nbsp; MAC address:0:50:56:c0:0:1:<br/>&nbsp;&nbsp;&nbsp; address:/fe80:0:0:0:3451:e274:322a:fd9f null null<br/>&nbsp;&nbsp;&nbsp; address:/172.16.160.1 /255.255.255.0 /255.255.255.255</pre>
            or
            the following (on Linux/UNIX):<br/>
            <pre>0 : eth0(null)<br/>&nbsp; &nbsp; datalink: EN10MB(Ethernet)<br/>    MAC address:0:c:29:fb:6c:df:<br/>    address:/172.16.32.129 /255.255.255.0 / 172.16.32.255</pre>
            <div style="text-align: right;"><a href="index.html#toc">Back
                to Table of Contents</a>
                <hr style="width: 100%; height: 2px;"/>
            </div>
            <h3><a name="open"></a>Open a network interface</h3>Once
            you obtain the list of network interfaces and choose which network
            interface to captuer packets from, you can open the interface by
            using&nbsp;<a
                href="../javadoc/jpcap/JpcapCaptor.html#openDevice(jpcap.NetworkInterface, int, boolean, int)">JpcapCaptor.openDevice()</a>
            method. The following piece of code illustrates how to open an network
            interface.<br/><br/>
            <pre class="code">NetworkInterface[] devices = JpcapCaptor.getDeviceList();<br/>int index=...;  // set index of the interface that you want to open.<br/><br/>//Open an interface with openDevice(NetworkInterface intrface, int snaplen, boolean promics, int to_ms)<br/>JpcapCaptor captor=JpcapCaptor.openDevice(device[index], 65535, false, 20);<br/></pre>
            <br/>When
            calling the&nbsp;<a
                href="../javadoc/jpcap/JpcapCaptor.html#openDevice(jpcap.NetworkInterface, int, boolean, int)">JpcapCaptor.openDevice()</a>
            method, you can specify the following parameters:<br/>&nbsp;<table style="text-align: left; width: 100%;"
                                                                               border="0" cellpadding="2"
                                                                               cellspacing="2">
            <tbody>
            <tr>
                <td style="width: 20%;"><span style="font-weight: bold;">Name:</span></td>
                <td><span style="font-weight: bold;">Purpose</span></td>
            </tr>
            <tr>
                <td><span style="font-style: italic;">NetworkInterface intrface</span></td>
                <td>Network
                    interface that you want to open.
                </td>
            </tr>
            <tr>
                <td><span style="font-style: italic;">int snaplen</span></td>
                <td>Max
                    number of bytes to capture at once.
                </td>
            </tr>
            <tr>
                <td style="vertical-align: top;"><span style="font-style: italic;">boolean promics</span></td>
                <td>True
                    if you want to open the interface in promiscuous mode, and
                    otherwise&nbsp;false.<br/>
                    <div style="margin-left: 40px;">In
                        promiscuous mode, you can&nbsp;capture packets every packet from the
                        wire, i.e., even if its source or destination MAC address is not same
                        as the MAC address of the interface you are opening.<br/>In
                        non-promiscuous mode, you can only capture packets send and received by
                        your host.
                    </div>
                </td>
            </tr>
            <tr>
                <td><span style="font-style: italic;">int to_ms</span></td>
                <td>Set
                    a capture timeout value in milliseconds.
                </td>
            </tr>
            </tbody>
        </table>
            <br/><a href="../javadoc/jpcap/JpcapCaptor.html#openDevice(jpcap.NetworkInterface, int, boolean, int)">JpcapCaptor.openDevice()</a>&nbsp;returns
            an instance of <a href="../javadoc/jpcap/JpcapCaptor.html">JpcapCaptor</a>.
            You can then call several methods of the&nbsp;<a href="../javadoc/jpcap/JpcapCaptor.html">JpcapCaptor</a>
            class to actually capture packets from the network interface.<br/><br/>
            <div style="text-align: right;"><a href="index.html#toc">Back
                to Table of Contents</a>
                <hr style="width: 100%; height: 2px;"/>
            </div>
            <h3><a name="capture"></a>Capture packets from
                the network interface</h3>Once you obtain an instance of of <a href="../javadoc/jpcap/JpcapCaptor.html">JpcapCaptor</a>,
            you can capture packets from the interface.<br/><br/>There
            are two major approaches to capture packets using a <a
                href="../javadoc/jpcap/JpcapCaptor.html">JpcapCaptor</a>
            instance: using a callback method, and capturing packets one-by-one.<br/><br/><span
                style="font-style: italic; text-decoration: underline;">Using
a callback method</span><br/><br/>In this approach,
            you implement a callback method to process captured packets, and then
            pass the callback method to Jpcap so that Jpcap calls it back every
            time it captures a packet. Let's see how you can do this approach in
            detail.<br/><br/>First, you implement a callback method
            by defining a new class which implements the <a
                href="../javadoc/jpcap/PacketReceiver.html">PacketReceiver</a>
            interface. The <a href="../javadoc/jpcap/PacketReceiver.html">PacketReceiver</a>
            interface defines &nbsp;a <a href="../javadoc/jpcap/PacketReceiver.html#receivePacket(jpcap.packet.Packet)">receivePacket()</a>
            method, so you need to implement a <a
                href="../javadoc/jpcap/PacketReceiver.html#receivePacket(jpcap.packet.Packet)">receivePacket()</a>
            method in your class.<br/><br/>The following class
            implement a <a href="../javadoc/jpcap/PacketReceiver.html#receivePacket(jpcap.packet.Packet)">receivePacket()</a>
            method which simply prints out a captured packet.<br/><br/>
            <pre class="code">class PacketPrinter implements PacketReceiver {<br/>  //this method is called every time Jpcap captures a packet<br/>  public void receivePacket(Packet packet) {<br/>    //just print out a captured packet<br/>    System.out.println(packet);<br/>  }<br/>}</pre>
            <br/>Then, you can call either <a
                href="../javadoc/jpcap/JpcapCaptor.html#processPacket(int, jpcap.PacketReceiver)">JpcapCaptor.processPacket()</a>
            or <a href="../javadoc/jpcap/JpcapCaptor.html#loopPacket(int, jpcap.PacketReceiver)">JpcapCaptor.loopPacket()</a>
            methods to start capturing using the callback method. When calling&nbsp;<a
                href="../javadoc/jpcap/JpcapCaptor.html#processPacket(int, jpcap.PacketReceiver)">processPacket()</a> or&nbsp;<a
                href="../javadoc/jpcap/JpcapCaptor.html#loopPacket(int, jpcap.PacketReceiver)">loopPacket()</a>
            method, you can also specify the number of packets to capture before
            the method returns. You can specify -1 to continue capturing packets
            infinitely. <br/><br/>
            <pre class="code">JpcapCaptor captor=JpcapCaptor.openDevice(device[index], 65535, false, 20);<br/><br/>//call processPacket() to let Jpcap call PacketPrinter.receivePacket() for every packet capture.<br/>captor.processPacket(10,new PacketPrinter());<br/><br/>captor.close();<br/></pre>
            <br/>The two methods for callback,&nbsp;<a
                href="../javadoc/jpcap/JpcapCaptor.html#processPacket(int, jpcap.PacketReceiver)">processPacket()</a>
            and&nbsp;<a href="../javadoc/jpcap/JpcapCaptor.html#loopPacket(int, jpcap.PacketReceiver)">loopPacket()</a>,
            are very similar. Usually you might want to use&nbsp;<a
                href="../javadoc/jpcap/JpcapCaptor.html#processPacket(int, jpcap.PacketReceiver)">processPacket()</a>
            because it supports timeout and non_blocking mode, while&nbsp;<a
                href="../javadoc/jpcap/JpcapCaptor.html#loopPacket(int, jpcap.PacketReceiver)">loopPacket()</a> doesn't.<br/><br/><span
                style="font-style: italic; text-decoration: underline;">Capturing
packets one-by-one<br/><br/></span>Using
            a callback method is a little bit tricky because you don't know when
            the callback method is called by Jpcap. If you don't want to use a
            callback method, you can also capture packets using the <a
                href="../javadoc/jpcap/JpcapCaptor.html#getPacket()">JpcapCaptor.getPacket()</a> method.<br/><br/><a
                href="../javadoc/jpcap/JpcapCaptor.html#getPacket()">getPacket()</a> method simply returns a captured
            packet. You can (or have to) call <a href="../javadoc/jpcap/JpcapCaptor.html#getPacket()">getPacket()</a>
            method multiple times to capture consecutive packets.<br/><br/>The following&nbsp;sample code&nbsp;also
            prints out captured packets.<br/><br/>
            <pre class="code">JpcapCaptor captor=JpcapCaptor.openDevice(device[index], 65535, false, 20);<br/><br/>for(int i=0;i&lt;10;i++){<br/>  //capture a single packet and print it out<br/>  System.out.println(captor.getPacket());<br/>}<br/><br/>captor.close();<br/></pre>
            <br/>
            <div style="text-align: right;"><a href="index.html#toc">Back
                to Table of Contents</a>
                <hr style="width: 100%; height: 2px;"/>
            </div>
            <span style="font-style: italic; text-decoration: underline;"></span>
            <h3><a name="set"></a>Set capturing filter</h3>In Jpcap, you can set a
            filter so that Jpcap doesn't capture unwanted packets. For example, if
            you only want to capture TCP/IPv4 packets, you can set a filter as
            following:<br/><br/>
            <pre class="code">JpcapCaptor captor=JpcapCaptor.openDevice(device[index], 65535, false, 20);<br/>//set a filter to only capture TCP/IPv4 packets<br/>captor.setFilter("ip and tcp", true);</pre>
            <br/>The
            filter expression "ip and tcp" means to to "keep only the packets that
            are both IPv4 and TCP and deliver them to the application". <br/><br/>By
            properly setting a filter, you can reduce the number of packets to
            examine, and thus can improve the performance of your application.<br/><br/>You can check the following
            homepage for more details about filter expression.<br/><br/><a href="http://home.insight.rr.com/procana/">Designing
            Capture Filters for Ethereal/Wireshark</a>
            <div style="text-align: right;"><a href="index.html#toc">Back
                to Table of Contents</a>
                <hr style="width: 100%; height: 2px;"/>
            </div>
            <h3><span style="font-style: italic; text-decoration: underline;"></span><a name="save"></a>Save captured
                packets
                into a file</h3>You
            can save captured packets into a binary file so that you can later
            retrieve them using Jpcap or other applications which supports reading
            a tcpdump format file.<br/><br/>To save captured packets, you first need to open a file by calling <a
                href="../javadoc/jpcap/JpcapWriter.html#openDumpFile(jpcap.JpcapCaptor, java.lang.String)">JpcapWriter.openDumpFile()</a>
            method with an instance of&nbsp;<a href="../javadoc/jpcap/JpcapCaptor.html">JpcapCaptor</a> which was used
            to capture packets, and a String filename.<br/><br/>
            <pre class="code">JpcapCaptor captor=JpcapCaptor.openDevice(device[index], 65535, false, 20);<br/>//open a file to save captured packets<br/>JpcapWriter writer=JpcapWriter.openDumpFile(captor,"yourfilename");</pre>
            <br/>Once you obtained an instance of <a href="../javadoc/jpcap/JpcapWriter.html">JpcapWriter</a> through&nbsp;<a
                href="../javadoc/jpcap/JpcapWriter.html#openDumpFile(jpcap.JpcapCaptor, java.lang.String)">openDumpFile()</a>
            method, you can save captured packets using <a
                href="../javadoc/jpcap/JpcapWriter.html#writePacket(jpcap.packet.Packet)">JpcapWriter.writePacket()</a>
            method. After you saved all the packets you want to save, you&nbsp;need to call <a
                href="../javadoc/jpcap/JpcapWriter.html#close()">JpcapWriter.close()</a> method to close the opened
            file.<br/><br/>The following sample code, combined with the above code, captures and saves first 100 packets
            captured.<br/><br/>
            <pre class="code">for(int i=0;i&lt;10;i++){<br/>  //capture a single packet<br/>  Packet packet=captor.getPacket();<br/>  //save it into the opened file<br/>  writer.writePacket(packet);<br/>}<br/>writer.close();</pre>
            <br/>
            <div style="text-align: right;"><a href="index.html#toc">Back
                to Table of Contents</a>
                <hr style="width: 100%; height: 2px;"/>
            </div>
            <h3><a name="read"></a>Read saved packets from
                a file</h3>In Jpcap, you can read the packets you saved using <a
                href="../javadoc/jpcap/JpcapWriter.html">JpcapWriter</a> by opening the file using <a
                href="../javadoc/jpcap/JpcapCaptor.html#openFile(java.lang.String)">JpcapCaptor.openFile()</a> method.
            Similar to&nbsp;<a
                href="../javadoc/jpcap/JpcapCaptor.html#openDevice(jpcap.NetworkInterface, int, boolean, int)">JpcapCaptor.openDevice()</a>
            method, <a href="../javadoc/jpcap/JpcapCaptor.html#openFile(java.lang.String)">JpcapCaptor.openFile()</a>
            method also returns an instance of <a href="../javadoc/jpcap/JpcapCaptor.html">JpcapCaptor</a> class. So you
            can use the same ways described in <a href="index.html#capture">Capture packets from the
            network interface</a> section to read packets from the file. For example, you can read and print out saved
            packets from a file as follows:<br/><br/>
            <pre class="code">//open a file to read saved packets<br/>JpcapCaptor captor=JpcapCaptor.openFile("yourfilename");<br/><br/>while(true){<br/>  //read a packet from the opened file<br/>  Packet packet=captor.getPacket();<br/>  //if some error occurred or EOF has reached, break the loop<br/>  if(packet==null || packet==Packet.EOF) break;<br/>  //otherwise, print out the packet<br/>  System.out.println(packet);<br/>}<br/><br/>captor.close();</pre>
            <br/>
            <div style="text-align: right;"><a href="index.html#toc">Back
                to Table of Contents</a>
                <hr style="width: 100%; height: 2px;"/>
            </div>
            <h3><a name="send"></a>Send packets through a
                network interface</h3>You can also send packets to the network using Jpcap. &nbsp;To send a packet, you
            need to obtain an instance of <a href="../javadoc/jpcap/JpcapSender.html">JpcapSender</a> by calling either
            <a href="../javadoc/jpcap/JpcapSender.html#openDevice(jpcap.NetworkInterface)">JpcapSender.openDevice()</a>
            or <a
                href="../javadoc/jpcap/JpcapCaptor.html#getJpcapSenderInstance()">JpcapCaptor.getJpcapSenderInstance()</a>
            methods.<br/><br/>Once you obtain an instance of <a href="../javadoc/jpcap/JpcapSender.html">JpcapSender</a>,
            you can pass an instance of <a href="../javadoc/jpcap/packet/Packet.html">Packet</a> class to <a
                href="../javadoc/jpcap/JpcapSender.html#sendPacket(jpcap.packet.Packet)">JpcapSender.sendPacket()</a>
            method.<br/><br/>The following sample code sends a TCP/IPv4/Ethernet packet onto a network
            interface.<br/><br/>
            <pre class="code">//open a network interface to send a packet to<br/>JpcapSender sender=JpcapSender.openDevice(devices[index]);<br/><br/>//create a TCP packet with specified port numbers, flags, and other parameters<br/>TCPPacket p=new TCPPacket(12,34,56,78,false,false,false,false,true,true,true,true,10,10);<br/><br/>//specify IPv4 header parameters<br/>p.setIPv4Parameter(0,false,false,false,0,false,false,false,0,1010101,100,IPPacket.IPPROTO_TCP,<br/>  InetAddress.getByName("www.microsoft.com"),InetAddress.getByName("www.google.com"));<br/><br/>//set the data field of the packet<br/>p.data=("data").getBytes();<br/><br/>//create an Ethernet packet (frame)<br/>EthernetPacket ether=new EthernetPacket();<br/>//set frame type as IP<br/>ether.frametype=EthernetPacket.ETHERTYPE_IP;<br/>//set source and destination MAC addresses<br/>ether.src_mac=new byte[]{(byte)0,(byte)1,(byte)2,(byte)3,(byte)4,(byte)5};<br/>ether.dst_mac=new byte[]{(byte)0,(byte)6,(byte)7,(byte)8,(byte)9,(byte)10};<br/><br/>//set the datalink frame of the packet p as ether<br/>p.datalink=ether;<br/><br/>//send the packet p<br/>sender.sendPacket(p);<br/><br/>sender.close();<br/></pre>
            <br/>
            <div style="text-align: right;"><a href="index.html#toc">Back
                to Table of Contents</a><br/></div>
            <hr style="width: 100%; height: 2px;"/>
            <div style="text-align: right;">Jpcap documentation.
                Copyright (c) 2007 Keita Fujii. All rights reserved.
            </div>
        </div>
    </div>
</div>
</body>
</html>
